package cn.lg.soar.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 流工具
 * @author luguoxiang 469599794@qq.com
 * @Date: 2024/1/24 18:12
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface StreamUtil {

    /**
     * 输入流转字节数组
     * @param is
     * @return
     */
    static byte[] inputStreamToBytes(InputStream is) {
        return inputStreamToByteArrayOutputStream(is).toByteArray();
    }

    /**
     * 转数组输出流
     * @param is
     * @return
     */
    static ByteArrayOutputStream inputStreamToByteArrayOutputStream(InputStream is) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            return bos;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字节数组转输入流
     * @param bytes
     * @return
     */
    static InputStream bytesToInputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }

    /**
     * 字节输出流转输入流
     * @param byteArrayOutputStream
     * @return
     */
    static InputStream byteArrayOutputStreamToInputStream(ByteArrayOutputStream byteArrayOutputStream) {
        return bytesToInputStream(byteArrayOutputStream.toByteArray());
    }

    /**
     * 输入流复制
     * @param is
     * @return
     */
    static InputStream copy(InputStream is) {
        return new ByteArrayInputStream(
                inputStreamToBytes(is)
        );
    }

}
